package com.weir.oauth2.authority.service.impl;

import com.weir.oauth2.feign.UserClient;
import com.weir.permissions.vo.UserInfo;

import java.util.ArrayList;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

	private static final Logger LOGGER = LoggerFactory.getLogger(MyUserDetailsServiceImpl.class);
	@Autowired
	private UserClient userClient;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		LOGGER.info("MyUserDetailsServiceImpl-----------");
		UserInfo userInfo = userClient.getUser(username);
		
		Collection<GrantedAuthority> collection = new ArrayList<>();
		for (String s : userInfo.getAuthorities()) {
			collection.add(new SimpleGrantedAuthority(s));
		}
		User user = new User(username, userInfo.getPassword(), collection);
		return user;
	}
}
